package com.weipai.education.service.impl;

import com.weipai.education.dao.CustomerDao;
import com.weipai.education.dao.InventoryDao;
import com.weipai.education.dao.UserDao;
import com.weipai.education.enums.RetCode;
import com.weipai.education.enums.UserType;
import com.weipai.education.model.*;
import com.weipai.education.model.api.PageResult;
import com.weipai.education.model.api.Response;
import com.weipai.education.service.CustomerService;
import com.weipai.education.utils.OrderNumberUtils;
import com.weipai.education.utils.SessionUserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: 曹朋飞
 * @Date: 2018/12/10 17:21
 */
@Service
public class CustomerServiceImpl implements CustomerService{
    
    @Autowired
    private CustomerDao customerDao;
    @Autowired
    private SessionUserUtil sessionUserUtil;
    @Autowired
    private InventoryDao inventoryDao;
    @Autowired
    private UserDao userDao;

    @Override
    @Transactional(readOnly=false, propagation = Propagation.REQUIRED)
    public Response save(Customer customer, String goodsBarCode, String productId) {

        Response response = new Response();
        if(null !=customer.getId()){
            customerDao.update(customer);
            response.setCode(RetCode.SUCCESS);
            return response;
        }else{
            String[] fields;
            String userId = sessionUserUtil.getUser().getId().toString();
            if(goodsBarCode!=null && !"".equals(goodsBarCode)){
                fields = goodsBarCode.split("\n");

                String tempUser = userId;
                User user = userDao.selectByPrimaryKey(userId); //自己的信息
                if (user.getType() == UserType.HQ_USER.getType()) { //如归是平台的账号
                    tempUser = "-1";
                }

                //验证货号，减库存，加出库记录
                Response returnMsg =  verifyInventory(0,tempUser,fields,productId,1);
                if(returnMsg.getCode() != 200){
                    return returnMsg;
                }
                customer.setUserId(Integer.parseInt(userId)).setTakeGoodsNumber(fields.length);
            }else {
                fields=new String[0];
                customer.setUserId(Integer.parseInt(userId)).setTakeGoodsNumber(fields.length);
            }

            customer.setStatus(0);
            customerDao.insert(customer);

            //添加拿货记录
            //y_cus_take_goods表的记录
            if(fields.length > 0){
                for (Integer i=0;i<fields.length;i++){
                    CusTakeGoods cusTakeGoods = new CusTakeGoods();
                    cusTakeGoods.setCustomerId(customer.getId()).setGoodsBarCode(fields[i]).setProductId(Integer.parseInt(productId));
                    customerDao.insertCusTakeGoods(cusTakeGoods);
                }
            }

            response.setCode(RetCode.SUCCESS);
            return response;

            //库存处理
           // return verifyInventory(customer.getId(), userId, fields, productId);
        }
    }

    /**
     * 库存处理
     * @param customerId
     * @param userId
     * @param fields
     * @param productId
     * @return
     */
    @Transactional(readOnly=false, propagation = Propagation.REQUIRED)
    public Response verifyInventory(Integer customerId, String userId, String[] fields, String productId,Integer type){
        Response response = new Response();

        //验证库存数量
        Inventory inventory = inventoryDao.getInventory(userId, productId);
        if(inventory == null || inventory.getStock() < fields.length){
            response.setCode(RetCode.UNDER_STOCK);
            return response;
        }

        //验证我的库存是否有这个商品
        List<Integer> inventoryDetailId = new ArrayList<>();
        List<Map<String,Integer>> inventoryDetailInfo = new ArrayList<>();
        for(String fle : fields){
            //根据userId和goodsBarCode查询此账户下是否有这个商品
            InventoryDetail inventoryDetail = inventoryDao.getInventoryDetail(userId, productId, fle);
            if(null == inventoryDetail){
                response.setCode(RetCode.NOT_DATA);
                response.put("goodsBarCode", "未找到["+fle+"]商品");
                return response;
            }
            Map<String,Integer> tempMap = new HashMap<>();
            tempMap.put("isPrice",inventoryDetail.getIsPrice());
            tempMap.put("isDamage",inventoryDetail.getIsDamage());
            inventoryDetailInfo.add(tempMap);
            inventoryDetailId.add(inventoryDetail.getId());
        }
        if(type == 0){  //0 拿货验证 1天假客户验证， 添加客户提前拿不到客户id
            //添加拿货记录
            for(String field :fields){
                CusTakeGoods cusTakeGoods = new CusTakeGoods();
                cusTakeGoods.setCustomerId(customerId).setGoodsBarCode(field).setProductId(Integer.parseInt(productId));
                customerDao.insertCusTakeGoods(cusTakeGoods);
            }

            //更新拿货总量
            Map<String,Object> customerInfo = customerDao.getCustomerInfo(Integer.toString(customerId));
            Customer customer = new Customer();
            customer.setId((int)customerInfo.get("id"));
            customer.setTakeGoodsNumber((int)customerInfo.get("takeGoodsNumber"));
            customerDao.update(customer);
        }

        //减库存
        inventory.setStock(inventory.getStock() - fields.length);
        inventoryDao.updateByPrimaryKeySelective(inventory);

        //fields的商品从我库中删除
        inventoryDao.batchDeleteInventoryDetailById(inventoryDetailId);

        //出库记录
        InventoryOut out = new InventoryOut();
        String outOrderNumber = OrderNumberUtils.outTradeNo();
        out.setDeliverUserId(Integer.parseInt(userId)).setOutOrderNumber(outOrderNumber).setProductId(Integer.parseInt(productId))
                .setProductNumber(fields.length).setCustomerId(customerId).setStatus(1);
        inventoryDao.saveInventoryOut(out);

        //出库记录明细
        for(int i=0;i<=fields.length-1;i++){
            InventoryOutDetail inventoryOutDetail = new InventoryOutDetail();
            inventoryOutDetail.setOutOrderNumber(outOrderNumber).setGoodsBarCode(fields[i]).setIsPrice(inventoryDetailInfo.get(i).get("isPrice")).setIsDamage(inventoryDetailInfo.get(i).get("isDamage"));
            inventoryDao.saveInventoryOutDetail(inventoryOutDetail);
        }
        response.setCode(RetCode.SUCCESS);
        return response;
    }
    

    @Override
    public Response changeStatus(String id) {
        Response response = new Response();
        Customer customer = customerDao.selectByPrimaryKey(id);
        if(null!=customer){
            if(0 ==customer.getStatus()){
                customer.setStatus(-1);
            }else{
                customer.setStatus(0);
            }
            customerDao.update(customer);
            response.setCode(RetCode.SUCCESS);
        }else{
            response.setCode(RetCode.NOT_DATA);
        }
        return response;
    }

    @Override
    public Response list(Integer page, Integer size, String key, String type) {
        Response response = new Response();
        
        String userId = sessionUserUtil.getUser().getId().toString();
        if("own".equals(type)){
            Integer start = (page - 1) * size;
            List<Map<String, Object>> customer = customerDao.list(start, size, key, userId);
            Integer totalNum = customerDao.listAmount(key, userId);
            PageResult<Map<String, Object>> pageList = new PageResult<>(customer, page, size, totalNum);
            response.setCode(RetCode.SUCCESS);
            response.put("pageList", pageList);
            return response;
        }else{
            User user = userDao.selectByPrimaryKey(userId); //自己的信息
            if (user.getType() == UserType.HQ_USER.getType()) { //如果是平台的账号
                userId = "-1";

//            if (Integer.valueOf(userId) == 1) {
                Integer start = (page - 1) * size;
                List<Map<String, Object>> customer = customerDao.list(start, size, key, userId);
                Integer totalNum = customerDao.listAmount(key, userId);
                PageResult<Map<String, Object>> pageList = new PageResult<>(customer, page, size, totalNum);
                response.setCode(RetCode.SUCCESS);
                response.put("pageList", pageList);
                return response;
//            }
            }else{
                response.setCode(RetCode.PERMISSION_DENIED);
                return response;
            }
        }
//        if (Integer.valueOf(userId) == 1) {
//            if (null == type) {
//                //从session中获取userId
//                userId = null;
//            }
//            Integer start = (page - 1) * size;
//            List<Map<String, Object>> customer = customerDao.list(start, size, key, userId);
//            Integer totalNum = customerDao.listAmount(key, userId);
//            PageResult<Map<String, Object>> pageList = new PageResult<>(customer, page, size, totalNum);
//            response.setCode(RetCode.SUCCESS);
//            response.put("pageList", pageList);
//            return response;
//        }else {
//            response.setCode(RetCode. NO_CLIENT);
//            return response;
//        }
    }

    @Override
    public Response saveCusRecord(CusRecord cusRecord) {
        Response response = new Response();
        customerDao.saveCusRecord(cusRecord);
        response.setCode(RetCode.SUCCESS);
        return response;
    }

    @Override
    public Response getCustomerInfo(String customerId) {
        Response response = new Response();
        
        Map<String, Object> customerMap = customerDao.getCustomerInfo(customerId);
        if(customerMap != null){
            List<Map<String, Object>> list = customerDao.getCusTakeGoods(customerMap.get("id").toString());
            customerMap.put("goodsBarCode", list);
            response.setData(customerMap);
            response.setCode(RetCode.SUCCESS);
        }else{
            response.setCode(RetCode.NOT_DATA);
        }
        return response;
    }

    @Override
    public Response getCusRecord(String customerId) {
        Response response = new Response();
        List<Map<String, Object>> list = customerDao.getCusRecord(customerId);
        if(!list.isEmpty()){
            response.setCode(RetCode.SUCCESS);
            response.setData(list);
        }else{
            response.setCode(RetCode.NOT_DATA);
        }
        return response;
    }

    @Override
    @Transactional(readOnly=false, propagation = Propagation.REQUIRED)
    public Response saveCusTakeGoods(String customerId, String goodsBarCode, String productId) {
        String userId = sessionUserUtil.getUser().getId().toString();
        String[] fields = goodsBarCode.split("\n");
        User user = userDao.selectByPrimaryKey(userId); //自己的信息
        String tempUser = userId;
        if (user.getType() == UserType.HQ_USER.getType()) { //如归是平台的账号
            tempUser = "-1";
        }
        //库存处理
        return verifyInventory(Integer.parseInt(customerId), tempUser, fields, productId,0);
    }
}
